package main

import (
	"crypto"
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/pem"
	"io/ioutil"
	"net/http"
	"strings"
)

var rsakey *rsa.PrivateKey

func InitRSAKey() {
	var rawkey []byte
	var err error
	if strings.HasPrefix(config.Key, "http") {
		// load key from HTTP
		var resp *http.Response
		resp, err = httpClient.Get(config.Key)
		if err != nil {
			logger.Fatalf("load private key from HTTP failed, %s", err.Error())
		}
		defer resp.Body.Close()
		rawkey, err = ioutil.ReadAll(resp.Body)
		if err != nil {
			logger.Fatalf("load private key from HTTP failed, %s", err.Error())
		}
	} else {
		// load key from local file
		rawkey, err = ioutil.ReadFile(config.Key)
		if err != nil {
			if config.Key == "jetbrains.key" {
				logger.Fatalf("no private key found, exit.")
			}
			logger.Fatalf("read private key file error: %s", err.Error())
		}
	}
	logger.Debugf("loaded rawkey: \n%s", string(rawkey))
	block, _ := pem.Decode(rawkey)
	if block == nil {
		logger.Fatal("key file is in error format")
	}
	// init rsakey
	if rsakey, err = x509.ParsePKCS1PrivateKey(block.Bytes); err != nil {
		logger.Fatal(err.Error())
	}
}

func signResponse(bs []byte) ([]byte, error) {
	var nbs []byte
	md5 := crypto.MD5.New()
	if _, err := md5.Write(bs); err != nil {
		logger.Error(err.Error())
		return nbs, err
	}
	var hash []byte = md5.Sum(nil)
	return rsa.SignPKCS1v15(rand.Reader, rsakey, crypto.MD5, hash)
}
